package com.whisper.common.controller;

import com.whisper.common.exception.file.FileException;
import com.whisper.common.utils.StringUtils;
import com.whisper.common.utils.file.FileDownloadUtils;
import com.whisper.common.utils.file.FileUtils;
import com.whisper.common.utils.http.MimeConstant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.nio.file.Path;
import java.util.List;

@RestController
@RequestMapping("/profile")
public class ProfileResourceController {

    private static final Logger log = LoggerFactory.getLogger(ProfileResourceController.class);

//    @GetMapping("/{path}/**")
//    private void getProfile(@PathVariable("path") String path, HttpServletRequest request, HttpServletResponse response) {
//        // 获取请求路径
//        String servletPath = request.getServletPath();
//        // 获取url中携带真正的文件路径
//        String realPath = "/" + servletPath.substring(servletPath.indexOf(path));
//        String fileName = Paths.get(realPath).getFileName().toString();
//        try
//        {
//            if (!FileUtils.checkAllowDownload(fileName))
//            {
//                throw new Exception(StringUtils.format("文件名称({})非法，不允许下载。 ", fileName));
//            }
//            String realFileName = System.currentTimeMillis() + fileName.substring(fileName.indexOf("_") + 1);
//            String filePath = WhisperConfig.getProfile() + realPath;
//
//            response.setContentType(MimeConstant.getContentType(fileName));
//            FileUtils.setAttachmentResponseHeader(response, realFileName);
//            FileUtils.writeBytes(filePath, response.getOutputStream());
//        } catch (Exception e)
//        {
//            log.error("下载文件失败", e);
//            throw new FileException("下载文件失败");
//        }
//    }

    @GetMapping("/img/{filename}")
    private void getImgResource(@PathVariable("filename") String fileName, HttpServletRequest request, HttpServletResponse response) {
        List<Path> filePathList = FileDownloadUtils.findFilePath("/img", fileName);
        outFile(fileName, response, filePathList);
    }
    @GetMapping("/avatar/{filename}")
    private void getAvatarResource(@PathVariable("filename") String fileName, HttpServletRequest request, HttpServletResponse response) {
        List<Path> filePathList = FileDownloadUtils.findFilePath("/avatar", fileName);
        outFile(fileName, response, filePathList);
    }

    @GetMapping("/common/{filename}")
    private void getCommonResource(@PathVariable("filename") String fileName, HttpServletRequest request, HttpServletResponse response) {
        List<Path> filePathList = FileDownloadUtils.findFilePath("/common", fileName);
        outFile(fileName, response, filePathList);
    }

    private void outFile(@PathVariable("filename") String fileName, HttpServletResponse response, List<Path> filePathList) {
        String filePath = filePathList.get(0).toAbsolutePath().toString();
        try
        {
            if (!FileUtils.checkAllowDownload(fileName))
            {
                throw new Exception(StringUtils.format("文件名称({})非法，不允许下载。 ", fileName));
            }
            String realFileName = System.currentTimeMillis() + fileName.substring(fileName.indexOf("_") + 1);

            response.setContentType(MimeConstant.getContentType(fileName));
            FileUtils.setAttachmentResponseHeader(response, realFileName);
            FileUtils.writeBytes(filePath, response.getOutputStream());
        } catch (Exception e)
        {
            log.error("下载文件失败", e);
            throw new FileException("下载文件失败");
        }
    }
}
